<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="user-breadcrumb">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input placeholder="请输入用户名" v-model="queryStr" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="queryUserList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="success" plain @click="showUserAddDialog">添加用户</el-button>
      </el-col>
    </el-row>
    <!--
      el-table 表格组件
        data 用来给表格组件提供数据
        stripe 添加改属性后，启用隔行变色效果

      el-table-column 表格中的每一列
        label 每一列的标题名称
        width 每一列的宽度
        prop 表示数据中的属性名（字段名称）
     -->
    <el-table :data="userList" stripe>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话" width="180">
      </el-table-column>
      <el-table-column label="用户状态">
        <!--  scope.row 表示当前行的数据-->
        <template slot-scope="scope">
          <!--
            v-model 用来绑定数据
            active-color  启用时的颜色
            inactive-color 禁用时的颜色
           -->
          <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row.id,scope.row.mg_state)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" plain size="mini" icon="el-icon-edit" @click="showUserEditDialig(scope.row)"></el-button>
          <el-button type="danger" plain size="mini" icon="el-icon-delete" @click="delUserById(scope.row.id)"></el-button>
          <el-button type="success" plain icon="el-icon-check" size="mini">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：background 背景色 ，layout 分页显示的内容 ，total 总条数
    给current-page属性添加.sync修饰符后就可以设置当前页 -->
    <el-pagination background layout="prev, pager, next" :total="total" :page-size="pagesize" :current-page.sync="curPage"
    @current-change="changePage">
    </el-pagination>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="userAddDialog" @close="closeUserAddDialog">
    <el-form :model="userAddForm" :rules="userAddRules" ref="userAddForm">
      <el-form-item label="用户名" label-width="120px" prop="username">
        <el-input v-model="userAddForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" label-width="120px" prop="password">
        <el-input v-model="userAddForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" label-width="120px" prop="email">
        <el-input v-model="userAddForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机" label-width="120px" prop="mobile">
        <el-input v-model="userAddForm.mobile" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="userAddDialog = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </div>
  </el-dialog>
  <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="userEditDialog" @close="closeUserEditDialog">
    <el-form :model="userEditForm" :rules="userEditRules" ref="userEditForm">
      <el-form-item label="用户名" label-width="120px" prop="username">
        <el-input disabled :value="userEditForm.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" label-width="120px" prop="email">
        <el-input v-model="userEditForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机" label-width="120px" prop="mobile">
        <el-input v-model="userEditForm.mobile" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="userEditDialog = false">取 消</el-button>
      <el-button type="primary" @click="editUser">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>
<script>
// import axios from 'axios'
export default{
  created() {
    // console.log(this.$http === axios)
    // 发送请求获取数据
    this.getUsersList()
  },
  data() {
    return {
      userList: [],
      // 每页条数
      pagesize: 2,
      // 当前页
      curPage: 1,
      // 总条数
      total: 0,
      // 搜索内容
      queryStr: '',
      // 控制用户添加对话框的展示与隐藏
      userAddDialog: false,
      userAddForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userAddRules: {
        username: [
          // required:是否为必填项  ，message：当前校验失败时的提示，trigger：表单验证的触发时机，blur表示失去焦点时触发
          { required: true, message: '用户名为必填项', trigger: 'blur' },
          // min：最小长度，max：最大长度
          { min: 3, max: 6, message: '用户名长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码为必填项', trigger: 'blur' },
          { min: 3, max: 6, message: '密码长度在 3 到 6 个字符', trigger: 'blur' }
        ]
      },
      // 控制用户编辑对话框的展示与隐藏
      userEditDialog: false,
      userEditForm: {
        id: -1,
        username: '',
        email: '',
        mobile: ''
      },
      userEditRules: {
        mobile: [{
          pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
          message: '手机号码格式不正确',
          // 如果需要在值改变或者失去焦点的时候，都触发验证，可以传递两个
          // trigger: 'change, blur'

          // 当前值改变，就会触发
          trigger: 'change'
        }]
      }
    }
  },
  methods: {
    // curPage = 1 给参数添加默认值
    // 获取用户列表数据
    getUsersList(curPage = 1) {
      this.$http.get('/users', {
        params: {
          // 当前页
          pagenum: curPage,
          // 每页条数
          pagesize: 2,
          // 查询条件
          query: this.queryStr || ''
        }
        // 将token作为请求头，传递给服务器接口，这样才能正确的调用这个接口
        // headers: {
        //   Authorization: localStorage.getItem('token')
        // }
      })
        .then(res => {
          // console.log('请求成功', res)
          const {data, meta} = res.data
          if (meta.status === 200) {
            // 获取数据请求成功
            this.userList = data.users
            this.total = data.total
            this.curpage = data.pagenum
          }
        })
    },
    /**
     * 分页获取数据
     * 参数 curpage表示当前点击的页码
     */
    changePage(curPage) {
      console.log(curPage)
      this.getUsersList(curPage)
    },
    // 搜索
    queryUserList() {
      // console.log(this.queryStr)
      this.curPage = 1
      this.getUsersList()
    },
    // 启用或者禁用用户
    changeUserState(id, curState) {
      // console.log(id, curState)
      this.$http
        .put(`/users/${id}/state/${curState}`)
        .then(res => {
          // console.log(res)
          const {data, meta} = res.data
          if (meta.status === 200) {
            this.$message({
              type: 'success',
              message: data.mg_state === 0 ? '禁用成功' : '启用成功',
              duration: 1000
            })
          } else {
            this.$message({
              type: 'error',
              message: meta.msg,
              duration: 1000
            })
          }
        })
    },
    // 展示用户添加对话框
    showUserAddDialog() {
      this.userAddDialog = true
    },
    // 关闭对话框并且重置表单
    closeUserAddDialog() {
      // console.log('对话框关闭了')
      this.$refs.userAddForm.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.userAddForm.validate(valid => {
        if (valid) {
          // 成功
          // console.log('验证成功')
          this.$http.post('/users', this.userAddForm)
            .then(res => {
              console.log('res', res)
              const {meta} = res.data
              // 关闭对话框，重置表单(只要关闭对话框，就会自动触发对话框的关闭事件来重置表单），重新渲染列表数据
              if (meta.status === 201) {
                this.userAddDialog = false
                this.getUsersList()
                this.curPage = 1
              }
            })
        } else {
          // 失败
          console.log('验证失败')
          return false
        }
      })
    },
    // 删除用户
    delUserById(id) {
      // console.log(id)
      this.$confirm('确认删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.delete(`users/${id}`)
            .then(res => {
              console.log('res', res)
              const {meta} = res.data
              if (meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: meta.msg
                })
                this.getUsersList()
                this.curPage = 1
                // const index = this.userList.findIndex(item => item.id === id)
                // this.userList.splice(index, 1)
                // const totalPage = Math.ceil(this.userList.length / this.pageSize)
                // if (this.curPage > totalPage) {
                //   this.getUsersList(--this.curPage)
                // }
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示用户对话编辑框
    showUserEditDialig(curUser) {
      // console.log(curUser)
      // 先获取到当前用户的数据
      // 数据交给 userEditForm 后，就会展示在编辑对话框中
      for (const key in this.userEditForm) {
        this.userEditForm[key] = curUser[key]
      }
      this.userEditDialog = true
    },
    // 关闭对话框并且重置表单
    closeUserEditDialog() {
      this.$.refs.userEditForm.resetFields()
    },
    editUser() {
      this.$refs.userEditForm.validate(valid => {
        if (valid) {
          // 成功
          const {id, email, mobile} = this.userEditForm
          // console.log('验证成功')
          this.$http.put(`/users/${id}`, {
            email,
            mobile
          })
            .then(res => {
              console.log('res', res)
              const {data, meta} = res.data
              // 关闭对话框，重置表单(只要关闭对话框，就会自动触发对话框的关闭事件来重置表单），重新渲染列表数据
              if (meta.status === 200) {
                const editUser = this.userList.find(item => item.id === id)
                editUser.email = data.email
                editUser.mobile = data.mobile
                this.userEditDialog = false
                // this.getUsersList()
                // this.curPage = 1
              }
            })
        } else {
          // 失败
          console.log('验证失败')
          return false
        }
      })
    }
  }
}
</script>
<style>
  .user-breadcrumb{
    line-height: 40px;
    background-color: #d4dae0;
    font-size: 18px;
    padding-left: 10px;
  }
</style>
